<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" v-if="formShow" />
      </template>
      <template #toolbar_btns>
        <VButton auth="/pmc/base/asinConfig/enable" @click="handleStatus(1)">
          <VStatus :value="true" />
        </VButton>
        <VButton auth="/pmc/base/asinConfig/disable" @click="handleStatus(0)">
          <VStatus :value="false" />
        </VButton>

        <VButton auth="/pmc/base/asinConfig/batchSync" class="ml-auto" @click="onManuallySync"> 手动同步 </VButton>

        <VButton auth="/pmc/base/asinConfig/notAsin" type="primary" @click="notAsinQuery"> 未绑定ASIN </VButton>
        <VButton auth="/pmc/base/asinConfig/import" icon="Download" @click="onImport"> 导入 </VButton>
        <VButton auth="/pmc/base/asinConfig/export" @click="onExport"> <svg-icon icon-class="import" class="mr-[4px]" /> 导出 </VButton>



        <!-- <el-button @click="handleStatus(1)">
          <div class="dk-iconfont icon-CircleCheck text-[#3487FF]"></div>
          启用
        </el-button>
        <el-button @click="handleStatus(0)"><svg-icon icon-class="state_disabled" class="text-[red] mr-[4px]" />禁用</el-button>
        <el-button type="primary" class="ml-auto" @click="onManuallySync">手动同步</el-button>

        <el-button type="primary" @click="notAsinQuery">未绑定ASIN</el-button>
        <el-button icon="Download" @click="onImport">导入</el-button>
        <el-button @click="onExport">
          <span class="flex items-center"> <svg-icon icon-class="import" class="mr-[4px]" /> 导出 </span>
        </el-button> -->
      </template>

      <!-- 关联副店铺 -->
      <template #SubStoreName="{ row }">
        <template v-for="(item, i) in row.base_asin_store" :key="i">
          <VText :value="item.sub_store_name" :line="1" v-if="i < 2" />
        </template>
        <el-popover placement="left" :width="200" trigger="click" v-if="row.base_asin_store.length > 2">
          <div>
            <VText v-for="(item, i) in row.base_asin_store" :key="i" :value="item.sub_store_name" :line="1" />
          </div>
          <template #reference>
            <el-link type="primary" :underline="false">查看更多</el-link>
          </template>
        </el-popover>
      </template>
    </VTable>

    <!-- 弹窗 表单编辑 -->
    <ConfirmInput v-model="batchVisible" v-bind="currentConfirm" @submit="handleConfirmSubmit">
      <!-- SKU名称 -->
      <template #SkuTitle="{ form }">
        <div class="sku-title" v-if="form?.sku_title">
          <VText title="SKU名称" :value="form?.sku_title" line="1" />
        </div>
      </template>
    </ConfirmInput>
    <!-- 日志 -->
    <XLog ref="logRef" :api="asinManagementLog"></XLog>

    <!-- 导入 -->
    <DialogImport v-model:modelValue="visibleImport" :download-url="downloadUrl" :api="asinManagementImport" @refresh="query" />
    <!-- 导出中心 -->
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>

    <Goods ref="GoodsRef" />
  </VPage>
</template>

<script setup lang="jsx">
import {
  asinManagementList,
  // asinManagementDetail,
  // asinManagementCreate,
  // asinManagementEdit,
  asinManagementBatchUpdateField,
  asinManagementLog,
  asinManagementImport,
  asinManagementManuallySync,
} from "@/api/base"
import { getShopOptions, getPlatformsSites, amazonSkuDetail, productChannelSku } from "@/api"
import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, ref, toRefs } from "vue"

import XForm from "@/components/XForm/index.vue"
// 弹窗 表单编辑
import ConfirmInput from "@/components/ConfirmInput/index.vue"
// 日志
import XLog from "@/components/XLog"
const logRef = ref()
// 导入
import DialogImport from "@/components/DialogImport/index.vue"
const visibleImport = ref(false)
const downloadUrl = ref("https://xc2k-pmc.oss-cn-shenzhen.aliyuncs.com/import_template/asin%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx")
const onImport = async () => {
  visibleImport.value = true
}
// 导出中心
import DerivedCenter from "@/components/DerivedCenter"
const DerivedCenterRef = ref()
const onExport = () => {
  let rows = tableRef?.value.$table.getCheckboxRecords()
  let formData = tableRef?.value?.getQueryForm()
  let condition = {}
  if (rows?.length) {
    condition.id = rows.map((v) => v.id)
  } else {
    condition = formData
  }
  // 未绑定asin
  if (condition.asin == "false") {
    condition.asin = false
  }

  DerivedCenterRef.value.open({
    tag_name: "BASE_ASIN_LIST",
    condition,
  })
}

// 手动同步
import Goods from "./components/Goods/index.vue"
const GoodsRef = ref()

const onManuallySync = () => {
  GoodsRef.value.open()
  // asinManagementManuallySync
  // const ids = getSelectRow()
  // if (!ids.length) return false
  // ElMessageBox.confirm(`此操作将 同步 ${ids.length}条数据, 是否继续?`, "提示", {
  //   confirmButtonText: "确定",
  //   cancelButtonText: "取消",
  //   type: "warning",
  //   confirmButtonClass: "oms-message-confirm-button",
  // }).then(async () => {
  //   try {
  //     let params = {
  //       channel_sku_id: ids,
  //     }
  //     asinManagementManuallySync(params).then((res) => {
  //       ElMessage.success("操作成功")
  //       query()
  //     })
  //   } catch (e) {
  //     throw Error(e)
  //   }
  // })
}
// const getShopOpt = async (e) => {
//   console.log(e)
//   console.log(19987)
//   // getShopOptions
//   currentConfirm.value.form.site_code = originOption.value.sites.find((v) => v.value == e)?.label
//   // 获取店铺
//   let shops = (await getShopOptions({ platform_ids: [2], site_ids: [e] })).data
//   originOption.value.shops = shops.map((v) => ({ label: v.shop_name, value: v.shop_id }))

//   console.log(3333)
//   console.log(currentConfirm.value)
//   if (currentConfirm.value.form.goods_sku_recommended_platform?.length) {
//     let transportation_type = currentConfirm.value.form.goods_sku_recommended_platform.find((v) => v.site_code == currentConfirm.value.form.site_code)?.header_channel_id || ""
//     console.log(transportation_type)
//     currentConfirm.value.form.transportation_type = transportation_type
//   }
// }

const tableRef = ref()

const data = reactive({
  // 弹窗 表单编辑
  batchVisible: false,
  currentConfirm: {},
})
const { batchVisible, currentConfirm } = toRefs(data)
const batchOConfig = {
  // 批量修改运输类型
  transportation_type: {
    title: "批量修改运输类型",
    fieldOptions: [
      {
        field: "field_value",
        label: "运输类型",
        type: "select",
        // originField: "transportationOpt",
        originField: "Base.BaseAsinList.TransportationTypeEnum",
        options: { placeholder: "运输类型" },
        style: { width: "200px" },
      },
    ],
  },
  // 批量修改运营人员
  operator_user: {
    title: "批量修改运营人员",
    fieldOptions: [
      {
        field: "field_value",
        label: "运营人员",
        type: "cascader",
        style: { width: "200px" },
      },
    ],
  },
  // 批量修改计划人员
  planner_user: {
    title: "批量修改计划人员",
    fieldOptions: [
      {
        field: "field_value",
        label: "计划人员",
        type: "cascader",
        style: { width: "200px" },
      },
    ],
  },
  // 批量修ASIN活跃度
  activity_status: {
    title: "批量修ASIN活跃度",
    fieldOptions: [
      {
        field: "field_value",
        label: "ASIN活跃度",
        type: "select",
        originField: "Base.BaseAsinList.ActivityStatusEnum",
        // originField: "Base.BaseAsinList.IsNewEnum",
        style: { width: "200px" },
      },
    ],
    tips: "人工调整ASIN状态后，系统定时统计销量/库存时，不在自动变更",
  },
  // 详情 编辑
  // edit: {
  //   title: "详情",
  //   formOptions: { inline: true, labelPosition: "top", requireAsteriskPosition: "right" },
  //   form: { is_new: 1, sku_title: "", transportation_type: "" },
  //   fieldOptions: [
  //     {
  //       field: "is_new",
  //       label: "新品链接",
  //       type: "radio",
  //       options: {
  //         data: [
  //           { label: "否", value: 0 },
  //           { label: "是", value: 1 },
  //         ],
  //       },
  //     },
  //     { type: "br" },
  //     {
  //       field: "asin",
  //       label: "ASIN",
  //       show: ({ model }) => model.exchange_type1 != 1,
  //       style: { width: "200px" },
  //       onBlur: (e, form) => getProductChannelSku(form),
  //     },
  //     {
  //       field: "site_id",
  //       label: "国家",
  //       originField: "amazonSite",
  //       type: "select",
  //       options: { placeholder: "国家" },
  //       style: { width: "200px" },
  //       // change: (e) => getShopOpt(e),
  //       change: async (e, form) => {
  //         form.main_store_id = ""
  //         form.base_asin_store = []
  //         if (e) {
  //           // getShopOptions
  //           form.site_code = originOption.value.amazonSite.find((v) => v.value == e)?.label
  //           let shops = (await getShopOptions({ platform_ids: [2], country_ids: [e] })).data
  //           originOption.value.shops = shops.map((v) => ({ label: v.shop_name, value: v.shop_id }))

  //           // 运输类型
  //           if (form.goods_sku_recommended_platform?.length) {
  //             let transportation_type = form.goods_sku_recommended_platform.find((v) => v.site_code == form.site_code)?.header_channel_id || ""
  //             form.transportation_type = transportation_type
  //           }
  //         } else {
  //           originOption.value.shops = []
  //         }
  //       },
  //     },
  //     { field: "status", label: "状态", type: "switch" },

  //     {
  //       field: "sku",
  //       label: "SKU",
  //       style: { width: "320px" },
  //       onBlur: async (e, form) => {
  //         if (!e) return
  //         let goods = (await amazonSkuDetail({ sku: e }))?.data || {}
  //         if (goods.id) {
  //           form.sku_title = goods?.sku_cn_title
  //           form.sku_attr_img = goods?.attr_img
  //           form.goods_sku_recommended_platform = goods?.goods_sku_recommended_platform

  //           if (form.site_code) {
  //             let transportation_type = form.goods_sku_recommended_platform.find((v) => v.site_code == form.site_code)?.header_channel_id || ""
  //             form.transportation_type = transportation_type
  //           }
  //           // 获取sku 运营人员
  //           getProductChannelSku(form)
  //         } else {
  //           form.sku_title = ""
  //           form.sku_attr_img = ""
  //           form.transportation_type = ""
  //           ElMessage({ showClose: true, message: "SKU不存在", type: "warning" })
  //         }
  //       },
  //     },
  //     { field: "sku_title", slot: "SkuTitle", style: { width: "500px" } },
  //     {
  //       field: "main_store_id",
  //       label: "主店铺",
  //       type: "select",
  //       originField: "shops",
  //       style: { width: "320px" },
  //       change: (e, form) => getProductChannelSku(form),
  //     },
  //     {
  //       field: "base_asin_store",
  //       label: "关联副店铺",
  //       type: "select",
  //       multiple: true,
  //       collapseTags: true,
  //       isHandle: true,
  //       originField: "shops",
  //       style: { width: "320px" },
  //     },

  //     { field: "transportation_type", label: "运输类型", type: "select", originField: "Base.BaseAsinList.TransportationTypeEnum", style: { width: "320px" } },
  //     { field: "operator_user", label: "运营人员", type: "cascader", placeholder: "运营人员", style: { width: "200px" } },
  //     { field: "planner_user", label: "计划人员", type: "cascader", placeholder: "计划人员", style: { width: "200px" } },
  //   ],
  //   rules: {
  //     site_id: [{ required: true, message: "请选择国家", trigger: "change" }],
  //     sku: [{ required: true, message: "请输入SKU", trigger: "change" }],
  //     main_store_id: [{ required: true, message: "请选择主店铺", trigger: "change" }],
  //     operator_user: [{ required: true, message: "请选择运营人员", trigger: "change" }],
  //     planner_user: [{ required: true, message: "请选择计划人员", trigger: "change" }],
  //   },
  // },
}
// 获取sku 运营人员
const getProductChannelSku = (form) => {
  if (form.asin && form.sku && form.main_store_id) {
    productChannelSku({ sku: form.sku, asin: form.asin, shopId: form.main_store_id }).then((res) => {
      form.operator_user = res.data.operations_id
    })
  }
}

// 批量操作
const batchOptions = [
  {
    label: "批量修改运输类型",
    value: "transportation_type",
    permission: [],
  },
  {
    label: "批量修改运营人员",
    value: "operator_user",
    permission: [],
  },
  {
    label: "批量修改计划人员",
    value: "planner_user",
    permission: [],
  },
  {
    label: "批量修ASIN活跃度",
    value: "activity_status",
    permission: [],
  },
]

// 弹窗 表单编辑 打开
const batchOptionsEvent = async (e, params = {}) => {
  console.log(e)
  // 批量操作
  let ids = []
  let batchKey = ["transportation_type", "operator_user", "planner_user", "activity_status"]
  if (batchKey.includes(e)) {
    ids = getSelectRow()
    if (!ids.length) {
      return false
    }
  }
  let confirm = {}
  switch (e) {
    case "transportation_type": // 批量修改运输类型
      confirm = {
        ...batchOConfig.transportation_type,
        originOption: originOption.value,
        type: e,
        length: ids.length,
      }
      confirm.form = {
        field_name: e,
        ids,
      }
      break
    case "operator_user": // 批量修改运营人员
      confirm = {
        ...batchOConfig.operator_user,
        type: e,
        length: ids.length,
      }
      confirm.form = {
        field_name: e,
        ids,
      }
      break
    case "planner_user": // 批量修改计划人员
      confirm = {
        ...batchOConfig.planner_user,
        type: e,
        length: ids.length,
      }
      confirm.form = {
        field_name: e,
        ids,
      }
      break
    case "activity_status": // 批量修ASIN活跃度
      confirm = {
        ...batchOConfig.activity_status,
        originOption: originOption.value,
        type: e,
        length: ids.length,
      }
      confirm.form = {
        field_name: e,
        ids,
      }
      break
    // case "add": // 详情 新增
    //   confirm = {
    //     ...batchOConfig.edit,
    //     title: "新增",
    //     type: e,
    //     originOption: originOption.value,
    //   }
    //   confirm.originOption.shops = []
    //   confirm.form = JSON.parse(JSON.stringify(batchOConfig.edit.form))
    //   console.log(confirm)
    //   break
    // case "edit": // 详情 编辑
    //   confirm = {
    //     ...batchOConfig.edit,
    //     title: "编辑",
    //     type: e,
    //     originOption: originOption.value,
    //   }
    //   let { data } = await asinManagementDetail({ id: params.id })
    //   // 重置 关联副店铺 数据格式
    //   data.base_asin_store = data.base_asin_store?.map((v) => v.sub_store_id)
    //   confirm.form = data
    //   // 根据已有站点 查询店铺列表
    //   getShopOptions({ platform_ids: [2], country_ids: [confirm.form] }).then((res) => {
    //     originOption.value.shops = res.data.map((v) => ({ label: v.shop_name, value: v.shop_id }))
    //   })
    //   break
    default:
      break
  }
  currentConfirm.value = confirm
  batchVisible.value = true
}
// 弹窗 表单编辑 保存 关闭
const handleConfirmSubmit = async (param) => {
  console.log(currentConfirm.value)
  console.log(param)
  param = JSON.parse(JSON.stringify(param))
  try {
    let api = null
    switch (currentConfirm.value.type) {
      case "transportation_type": // 批量修改运输类型
        api = asinManagementBatchUpdateField
        break
      case "operator_user": // 批量修改运营人员
        api = asinManagementBatchUpdateField
        break
      case "planner_user": // 批量修改计划人员
        api = asinManagementBatchUpdateField
        break
      case "activity_status": // 批量修ASIN活跃度
        api = asinManagementBatchUpdateField
        break
      // case "add":
      //   api = asinManagementCreate
      //   if (param.base_asin_store?.length) {
      //     let base_asin_store = originOption.value.shops.filter((v) => param.base_asin_store.includes(v.value))
      //     param.base_asin_store = base_asin_store.map((v) => ({ sub_store_id: v.value, sub_store_name: v.label }))
      //   }
      //   if (!param.sku_title) {
      //     return ElMessage({ showClose: true, message: "请选择正确的SKU！", type: "warning" })
      //   }
      //   break
      // case "edit":
      //   api = asinManagementEdit
      //   if (param.base_asin_store?.length) {
      //     let base_asin_store = originOption.value.shops.filter((v) => param.base_asin_store.includes(v.value))
      //     param.base_asin_store = base_asin_store.map((v) => ({ sub_store_id: v.value, sub_store_name: v.label }))
      //   }
      //   if (!param.sku_title) {
      //     return ElMessage({ showClose: true, message: "请选择正确的SKU！", type: "warning" })
      //   }
      //   break
      default:
        break
    }
    // return
    const res = await api(param)
    ElMessage.success(res.message)

    batchVisible.value = false
    setTimeout(() => {
      currentConfirm.value = {}
      query()
    }, 100)
  } catch (error) {
    console.warn(error)
  }
}

// //获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  const arr = []
  getCheckboxRecords.map((e) => {
    arr.push(e.id)
  })
  return arr
}

// //启用
const handleStatus = (status) => {
  const ids = getSelectRow()
  if (!ids.length) {
    return false
  }
  ElMessageBox.confirm(`此操作将 ${status ? "启用" : "禁用"} ${ids.length}条数据, 是否继续?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "oms-message-confirm-button",
  }).then(async () => {
    try {
      let params = {
        ids,
        field_name: "status",
        field_value: status,
      }
      asinManagementBatchUpdateField(params).then((res) => {
        ElMessage.success("操作成功")
        query()
      })
    } catch (e) {
      throw Error(e)
    }
  })
}
// 查询
const query = () => {
  tableRef?.value.query()
}
// 枚举 数据
const originOption = ref({
  // transportationOpt: [
  //   { label: "快递", value: 10 },
  //   { label: "空运", value: 11 },
  //   { label: "快海运", value: 12 },
  //   { label: "慢海运(海卡)", value: 13 },
  //   { label: "铁运", value: 14 },
  //   { label: "卡航", value: 15 },
  //   { label: "邮政小包", value: 16 },
  //   { label: "专线小包", value: 17 },
  //   { label: "其他", value: 18 },
  // ],
  // amazonSite: [],
})

import {
  fieldList, // 搜索条件 配置
  tableColumns, // 列配置
} from "./config.jsx"
const formShow = ref(false)
//获取下拉数据
onMounted(async () => {
  await getOption()
  nextTick(() => (formShow.value = true))
})
const notAsinQuery = () => {
  tableRef?.value?.resetForm()
  tableRef?.value?.setFormField("asin", "false")
  tableRef?.value?.query()
}
import { getEnum, getAmazonSite } from "@/utils/enumUtils"
const getOption = async () => {
  let keys = ["Base.BaseAsinList.ActivityStatusEnum", "Base.BaseAsinList.StatusEnum", "Base.BaseAsinList.IsRequiresStockingEnum", "Base.BaseAsinList.TransportationTypeEnum"]
  const data = await getEnum(keys)
  keys.forEach((key) => {
    originOption.value[key] = data[key]
  })
  originOption.value.amazonSite = await getAmazonSite()
}

const formOption = ref({ inline: true })

// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      asin: "",
      activity_status: "",
      site_id: [],
      status: "",
      is_requires_stocking: "",
      skuRange: { type: "sku", value: "" },
      userRange: { type: "operator_user", value: "" },
    },
  },
  scrollY: { enabled: false },
  // rowConfig: { height: "auto" },
  showOverflow: false,
  columns: [],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let params = {
          page: page.pageNum,
          page_size: page.pageSize,
          ...form,
        }
        let { asin, skuRange } = tableRef?.value?.getForm()
        params[skuRange.type] = skuRange.value?.split("\n")?.filter((v) => !!v.trim())
        params[skuRange.type] = params[skuRange.type].map((v) => v.trim())
        // 未绑定asin
        if (asin == "false") {
          params.asin = false
        }
        console.log(params)
        return asinManagementList(params)
      },
    },
  },
})
const handleColumn = {
  title: "操作",
  width: 80,
  fixed: "right",
  slots: {
    default: ({ row }) => {
      // <el-button link type="primary" onClick={() => batchOptionsEvent("edit", row)}>
      //   编辑
      // </el-button>
      return [
        <div>
          <el-button link type="primary" onClick={() => logRef?.value.open({ id: row.id })}>
            日志
          </el-button>
        </div>,
      ]
    },
  },
}
tableOptins.columns = [{ type: "checkbox", fixed: "left", width: 40 }, ...tableColumns.value, handleColumn]
</script>
<style lang="scss" scoped>
.sku-title {
  width: 100%;
  padding: 8px;
  background: #eaf3ff;
  border-radius: 4px;
}
</style>
